<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
header('Content-type: text/JavaScript');
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set("display_errors","true");

include_once("file.common.php");

$path = req('path', '.');
$password = req('password');
$callbackName = req('callback');
$imagesizes = req('imagesizes', FALSE);
$ot = '';

if ($imagesizes == 'true') $imagesizes = TRUE;

if ($validCredentials !== TRUE) {
	if ($callbackName) {
		$ee = '';
		$ee .= "$callbackName({\n";
		$ee .= "result: false,\n";
		$ee .= "msg: \"invalid credentials\",\n";
		$ee .= "end: true\n";
		$ee .= "});";
		echo $ee;
	}
	exit(0);
}

	//
	// Get folder and file lists
	//
	$numdirs = 0;
	$numfiles = 0;
	$handle = opendir($path);
	if ($handle) {
	    while (false !== ($file = readdir($handle))) {
		$nm = $path.'/'.$file;
	        if(!is_dir($nm)) {
	            if (!is_link($nm) && substr($file,0,1) != '.') {
	                $filearr[] = $file;
	                $numfiles++;
	            }
	        }
	        else {
	            if (substr($file,0,1) != '.') {
	                $dirarr[$numdirs] = $file;
	                $numdirs++;
	            }
	        }
	    }
	    closedir($handle);
	} else $handle = "FAILURE";

	if ($numdirs > 1) sort($dirarr);
	if ($numfiles > 1) sort($filearr);

	// Collect file sizes and modification times
	if ($numfiles > 0) for ($i = 0; $i < $numfiles; $i++) {
		$nm = $path.'/'.$filearr[$i];
		$sizearr[] = filesize($nm);
		$timearr[] = filemtime($nm);
		if ($imagesizes) $imagarr[] = getimagesize($nm);
	}

	// Build JSON object

	$jdirs = $jfiles = $jsizes = $jtimes = $jimgsizes = '';

	if ($numdirs > 0) for ($i = 0; $i < $numdirs; $i++) {
		if ($i!=0) $jdirs .= ",";
		$jdirs .= '"' . $dirarr[$i] . '"';
	}
	if ($numfiles > 0) for ($i = 0; $i < $numfiles; $i++) {
		if ($i!=0) {
			$jfiles .= ",";
			$jsizes .= ",";
			$jtimes .= ",";
			if ($imagesizes) $jimgsizes .= ",";
		}
		$jfiles .= '"' . $filearr[$i] . '"';
		$jsizes .= $sizearr[$i];
		$jtimes .= $timearr[$i];
		if ($imagesizes) $jimgsizes .= '"' . $imagarr[$i][0] . 'x' . $imagarr[$i][1] . '"';
	}
	
	$result = true;

	$ot .= '{' . "\r\n";
	$ot .= "\"result\": " . ($result ? 'true' : 'false') . ",\r\n";
	$ot .= "\"dircnt\": $numdirs,\r\n";
	$ot .= "\"filecnt\": $numfiles,\r\n";
	$ot .= "\"handle\": \"$handle\",\r\n";
	$ot .= "\"dirpath\": \"$path\",\r\n";
	$ot .= "\"dirs\": ".'['.$jdirs.']'.",\r\n";
	$ot .= "\"files\": ".'['.$jfiles.']'.",\r\n";
	$ot .= "\"sizes\": ".'['.$jsizes.']'.",\r\n";
	if ($imagesizes) $ot .= "\"imgsizes\": ".'['.$jimgsizes.']'.",\r\n";
	$ot .= "\"times\": ".'['.$jtimes.']'."\r\n";

	$ot .= '}';


if ($callbackName) echo "$callbackName(unescape('" . rawurlencode($ot) . "'));";

?>